<?php
//业务类公共方法
use App\Models\ErrorLog;
use App\Models\FileUpload;
use Illuminate\Support\Facades\Storage;
/**
 * 生成错误记录
 * @method writeErrorLog
 * @author chengzhigang
 */
if (!function_exists('writeErrorLog')) {
    function writeErrorLog($e)
    {
        $error = array(
            'path' => url()->full(),
            'code' => $e->getCode(),
            'msg' => $e->getMessage(),
            'file' => $e->getFile(),
            'line' => $e->getLine(),
            'create_time' => date('Y-m-d H:i:s'),
        );
        ErrorLog::create($error);
    }
}

/**
 * 接口返回json
 * @method apiReturn
 * @author chengzhigang
 * @return msg 提示信息 code(1成功 2失败 3重新登录) data 返回数据 time 请求时间
 */
if (!function_exists('apiResponse')) {
    function apiResponse($msg = "", $code = 2, $data = "",$cookie=[])
    {
        $result = array(
            'code' => $code,
            'msg' => $msg,
            'data' => $data,
            'time' => date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']),
        );
        $response = response();
        $response = $response->json($result);
        if($cookie){
            foreach($cookie as $val){
                $response = $response->withCookie($val['name'],$val['value']);
            }
        }
        return $response;
    }
}

/**
 * layui数据表格接口返回json
 * @method layTableApi
 * @author chengzhigang
 * @return msg 提示信息 code(0成功 1失败) data 返回数据 count 数据总数
 */
if (!function_exists('layTableApi')) {
    function layTableApi($count, $data = [], $code = 0)
    {
        $result = array(
            'code' => $code,
            'msg' => '请求' . $code == 0 ? '成功' : '失败',
            'count' => $count,
            'data' => $data,
        );
        return json_encode($result);
    }
}

/**
 * 生成验证码key
 * @method createCodeKey
 * @author chengzhigang<1256699215@qq.com>
 */
if (!function_exists('createCodeKey')) {
    function createCodeKey($phone)
    {
        $sign = config('const.sign') . '-' . $phone;
        return md5(sha1($sign));
    }
}

/**
 * 生成用户密码
 * @method
 * @author chengzhigang<1256699215@qq.com>
 */
if (!function_exists('createUserPwd')) {
    function createUserPwd($password)
    {
        $sign = config('const.sign') . ':' . $password;
        return md5(sha1($sign));
    }
}

/**
 * 生成用户token
 * @param [type] $user_id
 * @method createUserToken
 * @author chengzhigang<1256699215@qq.com>
 */
if (!function_exists('createUserToken')) {
    function createUserToken($user_id)
    {
        $key = config('const.sign');
        return md5(sha1($key . uniqid(md5(time()), true) . '-' . $user_id));
    }
}

/**
 * 上传单文件方法
 * @method upload
 * @author chengzhigang<1256699215@qq.com>
 * @param $files 文件（单或多） $type文件类型  $fileConfig 文件配置
 * @return $data 单文件返回文件真实路径 多文件返回数组
 * @return ['status'=>1,'msg'=>'','data'=>$data] status 2失败 1成功
 */
if (!function_exists('upload')) {
    function upload($file, $fileType = 'image', $fileConfig = [])
    {
        if ($file) {
            //判断文件是否上传成功
            if ($file->isValid()) {
                //原文件名
                $originalName = $file->getClientOriginalName();
                //扩展名
                $ext = strtolower($file->getClientOriginalExtension());
                $size = $file->getClientSize(); //文件大小
                $type = $file->getClientMimeType();
                $fileNameTemp = $file->getRealPath() ? $file->getRealPath() : $file->getPathName();
                $hash = md5_file($fileNameTemp);
                //判断文件类型
                $config = config('filesystems.disks.config');
                if (!isset($config[$fileType])) {
                    return ['status' => 2, 'msg' => '文件类型不支持', 'data' => []];
                }
                $config = $config[$fileType];
                $fileExt = isset($fileConfig['ext']) ? $fileConfig['ext'] : $config['ext'];
                $fileSize = isset($fileConfig['size']) ? $fileConfig['size'] : $config['size'];
                $fileDir = isset($fileConfig['dir']) ? ($fileConfig['dir'] . '/' . date('Ymd')) : ($config['dir'] . date('Ymd'));
                if (strpos($fileExt, $ext) !== false) {
                    if ($size > $fileSize) {
                        return ['status' => 2, 'msg' => '请上传' . floatval($fileSize) / (1024 * 1024) . 'M以内的文件', 'data' => []];
                    }
                    if ($fileType == 'image') {
                        $fileUpload = FileUpload::where('hash', $hash)->first();
                        if (!empty($fileUpload)) {
                            return ['status' => 1, 'msg' => '上传成功', 'data' => $fileUpload->path];
                        }
                    }
                    //临时绝对路径
                    $filename = uniqid() . '.' . $ext;
                    $filePath = $fileDir . '/' . $filename;
                    if (Storage::disk('public')->put($filePath, file_get_contents($fileNameTemp))) {
                        $savePath = Storage::url($filePath);
                        //上传记录
                        $fileData = [];
                        $fileData['name'] = $originalName;
                        $fileData['ext'] = $ext;
                        $fileData['type'] = $type;
                        $fileData['size'] = $size;
                        $fileData['hash'] = $hash;
                        $fileData['path'] = $savePath;
                        $fileData['create_time'] = date('Y-m-d H:i:s');
                        FileUpload::create($fileData);
                        return ['status' => 1, 'msg' => '上传成功', 'data' => $savePath];
                    } else {
                        return ['status' => 2, 'msg' => '文件上传失败', 'data' => []];
                    }
                } else {
                    return ['status' => 2, 'msg' => '文件类型不支持', 'data' => []];
                }
            }
        } else {
            return ['status' => 2, 'msg' => '请上传文件', 'data' => []];
        }
    }
}

/**
 * 上传多文件方法
 * @method uploads
 * @author chengzhigang<1256699215@qq.com>
 * @param $files 文件（单或多） $type文件类型  $fileConfig 文件配置
 * @return $data 单文件返回文件真实路径 多文件返回数组
 * @return ['status'=>1,'msg'=>'','data'=>$data] status 2失败 1成功
 */
if (!function_exists('uploads')) {
    function uploads($files, $fileType = 'image', $fileConfig = [])
    {
        if (is_array($files)) {
            $data = [];
            foreach ($files as $file) {
                $result = upload($file, $fileType, $fileConfig);
                if ($result['status'] == 1) {
                    $data[] = $result['data'];
                } else {
                    return $result;
                }
            }
            return ['status' => 1, 'msg' => '上传成功', 'data' => $data];
        }
    }
}

if (!function_exists('arraySort')) {
    /**
     * 二维数组根据某个字段排序
     * @param array $array 要排序的数组
     * @param string $keys   要排序的键字段
     * @param string $sort  排序类型  SORT_ASC     SORT_DESC
     * @return array 排序后的数组
     */
    function arraySort($array, $keys, $sort = SORT_DESC)
    {
        $keysValue = [];
        foreach ($array as $k => $v) {
            $keysValue[$k] = $v[$keys];
        }
        array_multisort($keysValue, $sort, $array);
        return $array;
    }
}
